package com.jcbase.core.util;

import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.log4j.Logger;

import com.jcbase.core.pojo.User;

public class AdUtil2 {

	
	private static Logger log = Logger.getLogger(AdUtil2.class);
	 private String host, url, adminName, adminPassword;  
	 private LdapContext ctx  ;    
	    /** 
	     * 初始化ldap 
	     */  
	    @SuppressWarnings({ "unchecked", "rawtypes" })  
	    public void initLdap() {  
	    	String ad_host = "192.168.1.252:389";
	    	String ad_user = "34112@test.com";
	    	String ad_password = "user!123";
	    	String ad_safe_level = "simple";
//	    	SysConfig ad_host = SysConfig.me.findFirst("select * from sys_config where param = 'ad_host'");
//	    	SysConfig ad_user = SysConfig.me.findFirst("select * from sys_config where param = 'ad_user'");
//	    	SysConfig ad_password = SysConfig.me.findFirst("select * from sys_config where param = 'ad_password'");
//	    	SysConfig ad_safe_level = SysConfig.me.findFirst("select * from sys_config where param = 'ad_safe_level'");
	        // ad服务器  
	        this.host =ad_host; // AD服务器  
	        this.url = new String("ldap://" + host);// 默认端口为80的可以不用填写，其他端口需要填写，如ldap://xxx.com:8080  
	        this.adminName = ad_user;// 注意用户名的写法：User@domain.com  
	        this.adminPassword = ad_password;  
	        Hashtable HashEnv = new Hashtable();  
	        HashEnv.put(Context.SECURITY_AUTHENTICATION, ad_safe_level); // LDAP访问安全级别  
	        HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User  
	        HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password  
	        HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类  
	        HashEnv.put(Context.PROVIDER_URL, url);  
	        try {  
	            ctx = new InitialLdapContext(HashEnv,null);  
	            System.out.println("初始化ldap成功！");    

	        } catch (NamingException e) {  
	            e.printStackTrace();  
	            System.err.println("Throw Exception : " + e);  
	        }  
	    }  
	  
	    /** 
	     * 关闭ldap 
	     */  
	    public void closeLdap() {  
	        try {  
	            this.ctx.close();  
	        } catch (NamingException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	  
	   
	    /** 
	     *  获取所有域用户信息并封装成User对象
	     * @param type organizationalUnit:组织架构 group：用户组 user|person：用户 
	     * @param name 
	     * @return 
	     */  
	    public String GetADInfo(String type ,String filter ,String name) {  
	    	  
	        String userName = name; // 用户名称  
	        if (userName == null) {  
	            userName = "";  
	        }  
	        String company = "";  
	        String result = "";  
	        try {  
	            // 域节点  
	            String searchBase = "DC=test";  
	            // LDAP搜索过滤器类  
	            //cn=*name*模糊查询 cn=name 精确查询  
//	          String searchFilter = "(objectClass="+type+")";  
	            String searchFilter = "(&(objectClass="+type+")("+filter+"=*" + name + "*))";  
	            // 创建搜索控制器  
	            SearchControls searchCtls = new SearchControls();   
	            //  设置搜索范围  
	            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);   

	            // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果  
	            NamingEnumeration answer = ctx.search(searchBase, searchFilter,searchCtls);// Search for objects using the filter  
	            // 初始化搜索结果数为0  
	            int totalResults = 0;// Specify the attributes to return  
	            int rows = 0;  
	            while (answer.hasMoreElements()) {// 遍历结果集  
	                SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN  
	                ++rows;  
	                String dn = sr.getName();  
	                System.out.println(dn);  
	                Attributes Attrs = sr.getAttributes();// 得到符合条件的属性集  
	                if (Attrs != null) {  
	                    try {  
	                        for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore();) {  
	                            Attribute Attr = (Attribute) ne.next();// 得到下一个属性  
	                            System.out.println(" AttributeID=属性名："+ Attr.getID().toString());  
	                            // 读取属性值  
	                            for (NamingEnumeration e = Attr.getAll(); e.hasMore(); totalResults++) {  
	                                company = e.next().toString();  
	                                System.out.println("    AttributeValues=属性值："+ company);  
	                            }  
	                            System.out.println("    ---------------");  
	  
	                        }  
	                    } catch (NamingException e) {  
	                        System.err.println("Throw Exception : " + e);  
	                    }  
	                }// if  
	            }// while  
	            System.out.println("************************************************");  
	            System.out.println("Number: " + totalResults);  
	            System.out.println("总共用户数："+rows);  
	        } catch (NamingException e) {  
	            e.printStackTrace();  
	            System.err.println("Throw Exception : " + e);  
	        }  
	        return result;  
	    } 
	  
	  
	    public static void main(String args[]) {  
	    	  Properties env = new Properties();  
	          String adminName = "Administrator@test.com";//username@domain  
	          String adminPassword = "user!123";//password  
	          String ldapURL = "LDAP://192.168.1.252:389";//ip:port  
	          env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");  
	          env.put(Context.SECURITY_AUTHENTICATION, "simple");//"none","simple","strong"  
	          env.put(Context.SECURITY_PRINCIPAL, adminName);  
	          env.put(Context.SECURITY_CREDENTIALS, adminPassword);  
	          env.put(Context.PROVIDER_URL, ldapURL);  
	          try {  
	              LdapContext ctx = new InitialLdapContext(env, null);  
	              SearchControls searchCtls = new SearchControls();  
	              searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);  
	              String searchFilter = "(objectClass=User)";  
	              String searchBase = "DC=test,DC=com";  
	              String attributeNames[] = { "memberOf","cn","description"};// 定制返回属性  
//	               String[] attributeNames = { "memberOf", "name", "userPrincipalName", "objectClass", "objectGUID","sAMAccountName","description" };
	               searchCtls.setReturningAttributes(attributeNames);
	              NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter,searchCtls);    
	  			while (answer.hasMoreElements()) {
	  				SearchResult sr = (SearchResult) answer.next();
	  				 String dn = sr.getName();  
	                 System.out.println("dn=" +dn);  
	  				Attributes attrs = sr.getAttributes();
	  				if(attrs!=null){
	  					User user = new User();
	  					 for (NamingEnumeration<?> ne = attrs.getAll(); ne.hasMore();) {  
	  						  Attribute Attr = (Attribute) ne.next();// 得到下一个属性  
	  						 System.out.println("属性名："+ Attr.getID().toString());  
	  						 if("cn".equals(Attr.getID().toString())){
	  							NamingEnumeration<?> e = Attr.getAll();
		 	                      // 读取属性值  
		 	 	  				 while(e.hasMore()){
		 	 	  					String value = e.next().toString();
		 	 	  					user.setUser(value);
		 	 	                    System.out.println("属性值："+value);  
		 	 	                    break;
		 	 	  				 }
	  						 }
	  						if("memberOf".equals(Attr.getID().toString())){
	  							NamingEnumeration<?> e = Attr.getAll();
		 	                      // 读取属性值  
		 	 	  				 while(e.hasMore()){
		 	 	  					String value = e.next().toString();
		 	 	  					user.setGroup(value);
		 	 	                    System.out.println("属性值："+value);  
		 	 	                    break;
		 	 	  				 }
	  						 }
	  						if("description".equals(Attr.getID().toString())){
	  							NamingEnumeration<?> e = Attr.getAll();
		 	                      // 读取属性值  
		 	 	  				 while(e.hasMore()){
		 	 	  					String value = e.next().toString();
		 	 	  					user.setCommon(value);
		 	 	                    System.out.println("属性值："+value);  
		 	 	                    break;
		 	 	  				 }
	  						 }
	  					 }
	  					
	  				}
	  				
	  				
	  			}
	              ctx.close();  
	          }catch (NamingException e) {  
	              e.printStackTrace();  
	              System.err.println("Problem searching directory: " + e);  
	          }  
	      }  
	}  
